package com.hange.ymcc.mq;

import com.alibaba.fastjson.JSON;
import com.hange.ymcc.constant.Regexconstant;
import com.hange.ymcc.domain.MessageEmail;
import com.hange.ymcc.dto.MessageEmailDto;
import com.hange.ymcc.dto.UseridEmail;
import com.hange.ymcc.exception.BusinessException;
import com.hange.ymcc.exception.ErrorCode;
import com.hange.ymcc.service.IMessageEmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RocketMQMessageListener(
        topic = Regexconstant.ROCKETMQ_TOPIC_COURSE,
        selectorExpression = Regexconstant.ROCKETMQ_TAG_EMAIL,
        consumerGroup = "service-course-email-consumer")
public class MQEmailConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageEmailService messageEmailService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            String jsonStrMessage = new String(messageExt.getBody(), "UTF-8");
            MessageEmailDto messageEmailDto = JSON.parseObject(jsonStrMessage, MessageEmailDto.class);
            List<UseridEmail> useridEmail = messageEmailDto.getUseridEmailList();

            useridEmail.forEach(m -> {
                MessageEmail messageEmail = new MessageEmail();
                BeanUtils.copyProperties(messageEmailDto,messageEmail);
                messageEmail.setSendTime(new Date());
                messageEmail.setUserId(m.getUserid());
                messageEmail.setEmail(m.getEmail());
                messageEmailService.insert(messageEmail);

                // 发送邮件。。。。。。。  略
                log.info("邮件推送消息消费结果成功");
            });

        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }

    }
}
